/**
 * LoginAction.java
 * create by Lisq
 * date 2014-1-7
 */
package com.lsq.common.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lsq.common.service.ILoginService;
import com.lsq.student.entity.Student;
import com.lsq.teacher.entity.Teacher;

/**
 * @author Lisq
 */
@Namespace("/")
@Controller("loginAction")
@Scope(value="prototype")
public class LoginAction extends BaseAction {

	private static final long serialVersionUID = -182850052204093494L;

	private static final String STUDENT = "1";
	private static final String TEACHER = "2";
	private static final String ADMIN = "3";

	private String userName;
	private String password;
	private String type;

	@Autowired
	private ILoginService loginService;

	@Action(value = "login", results = {
			@Result(name = "student", type = "redirectAction", location = "stusys/findStudentScorePage"),
			@Result(name = "teacher", type = "redirectAction", location = "stusys/findTeacherScorePage"),
			@Result(name = "admin", type = "redirectAction", location = "manage/navigation"),
			@Result(name = ERROR, location = "/error.html"),
			@Result(name = "loginError", location = "/loginError.html") })
	public String login() {
		if (type.equals(STUDENT)) {
			Student student = loginService.validateStudent(userName, password);
			if (student != null) {
				session.put("currentUser", student);
				return "student";
			} else {
				return "loginError";
			}
		} else if (type.equals(TEACHER)) {
			Teacher teacher = loginService.validateTeacher(userName, password);
			if (teacher != null) {
				session.put("currentUser", teacher);
				return "teacher";
			} else {
				return "loginError";
			}
		} else if (type.equals(ADMIN)) {
			if (userName.equals("admin") && password.equals("1qaz2wsx")) {
				session.put("adminUserName", userName);
				session.put("adminPassword", password);
				return "admin";
			} else {
				return "loginError";
			}
		} else {
			return ERROR;
		}
	}

	@Action(value = "loginOut", results = { @Result(name = SUCCESS, location = "/login.html") })
	public String loginOut() {
		session.clear();
		return SUCCESS;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
